#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "capturewindow.h"
#include <QPainter>
#include <QPixmap>
#include <QRandomGenerator>
#include <QResizeEvent>
#include <QGraphicsView>
#include <QGraphicsOpacityEffect>
#include <QLabel>
#include <cmath>
#include <QPropertyAnimation>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , textAnimationGroup(nullptr)
    , particleScene(nullptr)
    , particleView(nullptr)
    , particleTimer(nullptr)
{
    ui->setupUi(this);

    // 初始化UI后设置动画
    setupTextAnimation();
    setupParticleEffects();
}

MainWindow::~MainWindow()
{
    // 清理文字动画资源
    if (textAnimationGroup) {
        textAnimationGroup->stop();
        delete textAnimationGroup;
    }

    // 清理字符效果
    for (QGraphicsOpacityEffect* effect : charEffects) {
        delete effect;
    }
    charEffects.clear();

    // 清理粒子效果资源
    if (particleTimer) {
        particleTimer->stop();
        delete particleTimer;
    }

    clearParticles();

    if (particleView) {
        delete particleView;
    }

    if (particleScene) {
        delete particleScene;
    }

    delete ui;
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    QMainWindow::resizeEvent(event);
    positionParticleView();
}

void MainWindow::positionParticleView()
{
    if (particleView) {
        particleView->setGeometry(rect());
    }

}

void MainWindow::setupTextAnimation()
{
    // 创建文字动画组
    textAnimationGroup = new QSequentialAnimationGroup(this);

    // 获取标题文本
    QString text = ui->titleLabel->text();

    // 移除现有文本（动画开始时为空）
    ui->titleLabel->setText("");

    // 为每个字符创建动画
    for (int i = 0; i < text.length(); ++i) {
        // 创建字符标签（作为titleLabel的子对象）
        QLabel *charLabel = new QLabel(ui->titleLabel);
        charLabel->setText(text.mid(i, 1));
        charLabel->setFont(ui->titleLabel->font());
        charLabel->setStyleSheet("color: rgba(208, 142, 55, 221);");
        charLabel->setAlignment(Qt::AlignCenter);

        // 计算字符位置（基于父标签）
        QRect parentRect = ui->titleLabel->rect();
        int charWidth = parentRect.width() / text.length();
        charLabel->setGeometry(i * charWidth, 0, charWidth, parentRect.height());

        // 创建透明度效果
        QGraphicsOpacityEffect *effect = new QGraphicsOpacityEffect(charLabel);
        effect->setOpacity(0.0); // 初始完全透明
        charLabel->setGraphicsEffect(effect);
        charEffects.append(effect);

        // 创建字符淡入动画
        QPropertyAnimation *charAnim = new QPropertyAnimation(effect, "opacity", this);
        charAnim->setDuration(200); // 每个字符动画时间
        charAnim->setStartValue(0.0);
        charAnim->setEndValue(1.0);
        charAnim->setEasingCurve(QEasingCurve::InOutQuad);

        // 添加到动画组
        textAnimationGroup->addAnimation(charAnim);
    }

    // 连接动画结束信号到粒子效果
    connect(textAnimationGroup, &QSequentialAnimationGroup::finished, [this]() {
        // 动画结束后启动粒子效果
        if (particleTimer) {
            particleTimer->start();
        }
    });

    // 启动文字动画
    textAnimationGroup->start();
}

void MainWindow::setupParticleEffects()
{
    // 创建粒子场景
    particleScene = new QGraphicsScene(this);

    // 创建粒子视图（覆盖整个窗口）
    particleView = new QGraphicsView(particleScene, this);
    particleView->setStyleSheet("background: transparent; border: none;");
    particleView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    particleView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    particleView->setFrameShape(QFrame::NoFrame);
    particleView->setRenderHint(QPainter::Antialiasing);
    particleView->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
    particleView->setSceneRect(rect());
    particleView->setAttribute(Qt::WA_TransparentForMouseEvents); // 允许鼠标事件穿透
    positionParticleView();

    // 创建粒子定时器（先创建但不启动）
    particleTimer = new QTimer(this);
    particleTimer->setInterval(30); // 约30FPS
    connect(particleTimer, &QTimer::timeout, this, &MainWindow::updateParticles);

    // 初始化粒子
    const int particleCount = 80;
    particles.reserve(particleCount);
    particleDirections.reserve(particleCount);
    particleOffsets.reserve(particleCount);

    // 获取标签位置
    QRect labelRect = ui->titleLabel->geometry();

    // 创建随机粒子
    QRandomGenerator* rng = QRandomGenerator::global();

    for (int i = 0; i < particleCount; ++i) {
        // 创建粒子图像（小圆点）
        int size = rng->bounded(4, 12);
        QPixmap particlePixmap(size, size);
        particlePixmap.fill(Qt::transparent);

        QPainter painter(&particlePixmap);
        painter.setRenderHint(QPainter::Antialiasing);

        // 随机粒子颜色（金色系）
        int alpha = rng->bounded(100, 200);
        QColor particleColor(208, 142, 55, alpha);
        painter.setBrush(particleColor);
        painter.setPen(Qt::NoPen);
        painter.drawEllipse(0, 0, size, size);
        painter.end();

        // 创建粒子项
        QGraphicsPixmapItem* particle = particleScene->addPixmap(particlePixmap);
        particle->setZValue(10); // 确保粒子在顶层

        // 计算相对于标签中心的偏移
        int offsetX = rng->bounded(-labelRect.width(), labelRect.width());
        int offsetY = rng->bounded(-labelRect.height(), labelRect.height());
        particleOffsets.append(QPointF(offsetX, offsetY));

        // 初始位置（基于标签位置）
        QPointF labelCenter = labelRect.center();
        particle->setPos(labelCenter.x() + offsetX, labelCenter.y() + offsetY);

        // 随机移动方向
        qreal dx = rng->generateDouble() * 100.0 - 50.0;
        qreal dy = rng->generateDouble() * 100.0 - 50.0;
        particleDirections.append(QPointF(dx, dy));

        // 添加到粒子列表
        particles.append(particle);
    }
}

void MainWindow::updateParticles()
{
    QRect labelRect = ui->titleLabel->geometry();
    QPointF labelCenter = labelRect.center();
    QRandomGenerator* rng = QRandomGenerator::global();

    for (int i = 0; i < particles.size(); ++i) {
        QGraphicsPixmapItem* particle = particles[i];
        QPointF direction = particleDirections[i];
        QPointF offset = particleOffsets[i];

        // 计算目标位置（基于标签中心+偏移）
        QPointF targetPos(labelCenter.x() + offset.x(), labelCenter.y() + offset.y());

        // 获取当前位置
        QPointF currentPos = particle->pos();

        // 计算向目标位置移动的向量
        QPointF toTarget = targetPos - currentPos;
        qreal distance = std::sqrt(toTarget.x()*toTarget.x() + toTarget.y()*toTarget.y());

        // 如果粒子离目标位置太远，直接重置位置
        if (distance > 1000) {
            particle->setPos(targetPos);
        } else {
            // 向目标位置移动
            QPointF moveVector = toTarget * 0.05;

            // 加上随机方向
            moveVector += direction;

            // 限制最大移动速度
            qreal speed = std::sqrt(moveVector.x()*moveVector.x() + moveVector.y()*moveVector.y());
            if (speed > 50.0) {
                moveVector = moveVector * (50.0 / speed);
            }

            // 更新位置
            particle->setPos(currentPos + moveVector);
        }

        // 随机改变方向
        if (rng->bounded(100) < 50) {
            qreal dx = rng->generateDouble() * 2.0 - 1.0;
            qreal dy = rng->generateDouble() * 2.0 - 1.0;
            particleDirections[i] = QPointF(dx, dy);
        }

        // 随机改变粒子透明度
        if (rng->bounded(100) < 5) {
            qreal newOpacity = rng->generateDouble() * 0.7 + 0.3;
            particle->setOpacity(newOpacity);
        }
    }
}

void MainWindow::clearParticles()
{
    // 清理粒子资源
    for (QGraphicsPixmapItem* particle : particles) {
        if (particle && particleScene) {
            particleScene->removeItem(particle);
            delete particle;
        }
    }
    particles.clear();
    particleDirections.clear();
    particleOffsets.clear();
}

void MainWindow::on_startButton_clicked()
{
    if (particleTimer) particleTimer->stop();
    clearParticles();
    capturewindow* captureWindow = new capturewindow();
    captureWindow->show();

    this->close();
}

